package cn.itcast.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import cn.itcast.constants.Constant;
import cn.itcast.tools.WeatherTools;

@Configuration
public class SpringAIConfig {

    @Bean
    public Advisor simpleLoggerAdvisor() {
        return new SimpleLoggerAdvisor();
    }

    @Bean
    public ChatMemory chatMemory() {
        return new InMemoryChatMemory();
    }

    @Bean
    public Advisor messageChatMemoryAdvisor(ChatMemory chatMemory) {
        return new MessageChatMemoryAdvisor(chatMemory);
    }

    /**
     * 创建并返回聊天记忆管理advisor的Spring Bean
     *
     * @param chatMemory 聊天记忆管理器实例
     * @return PromptChatMemoryAdvisor 实例，用于在聊天过程中维护上下文
     */
    @Bean
    public Advisor promptChatMemoryAdvisor(ChatMemory chatMemory) {
        return new PromptChatMemoryAdvisor(chatMemory);
    }

    /**
     * 创建并返回一个ChatClient的Spring Bean实例。
     *
     * @param builder 用于构建ChatClient实例的构建者对象
     * @return 构建好的ChatClient实例
     */
    // @Bean
    // public ChatClient chatClient(ChatClient.Builder builder,
    // Advisor simpleLoggerAdvisor,
    // Advisor messageChatMemoryAdvisor) {

    // return builder
    // .defaultSystem(Constant.SYSTEM_ROLE)
    // .defaultAdvisors(simpleLoggerAdvisor, messageChatMemoryAdvisor)
    // .build();
    // }

    @Bean
    public ChatClient chatClient(ChatClient.Builder builder,
            Advisor simpleLoggerAdvisor,
            Advisor messageChatMemoryAdvisor,
            Advisor promptChatMemoryAdvisor,
            // Advisor safeGuardAdvisor,
            WeatherTools weatherTools) {
        return builder
                .defaultSystem(Constant.SYSTEM_ROLE) // 设置默认的系统角色
                .defaultAdvisors(simpleLoggerAdvisor, promptChatMemoryAdvisor/* , safeGuardAdvisor */) // 设置默认的Advisor
                .defaultTools(weatherTools) // 设置默认的Tool
                .build();
    }

}
